package com.bawei.flink.demo;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.time.Duration;

public class SessionWindowDemo {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<String> lines = env.socketTextStream("cdh1", 9999);

        SingleOutputStreamOperator<Tuple2<Long, String>> maped = lines.map(new MapFunction<String, Tuple2<Long, String>>() {
            @Override
            public Tuple2<Long, String> map(String value) throws Exception {
                String[] arr = value.split(",");
                return Tuple2.of(Long.valueOf(arr[0]), arr[1]);
            }
        });

        SingleOutputStreamOperator<Tuple2<Long, String>> mapedWithWaterMarker = maped.assignTimestampsAndWatermarks(WatermarkStrategy.<Tuple2<Long, String>>forBoundedOutOfOrderness(Duration.ofSeconds(5)).withTimestampAssigner(new SerializableTimestampAssigner<Tuple2<Long, String>>() {
            @Override
            public long extractTimestamp(Tuple2<Long, String> element, long recordTimestamp) {
                return element.f0;
            }
        }));


        mapedWithWaterMarker.windowAll(EventTimeSessionWindows.withGap(Time.seconds(10)))
                .process(new ProcessAllWindowFunction<Tuple2<Long, String>, String, TimeWindow>() {

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                    @Override
                    public void process(Context context, Iterable<Tuple2<Long, String>> elements, Collector<String> out) throws Exception {
                        String windowStart = sdf.format(context.window().getStart());
                        String windowEnd = sdf.format(context.window().getEnd());
                        StringBuffer sb = new StringBuffer();
                        for(Tuple2<Long,String> element : elements) {
                            sb.append(element.f1+",");
                        }

                        String outStr = windowStart + "  ---->  " + windowEnd + "    " + sb.toString();
                        out.collect(outStr);
                    }
                })
                .print();

        env.execute();
    }
}
